﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Configuration;

namespace Common
{
    /// <summary>
    /// 发送邮件类
    /// </summary>
    public class SendMail
    {
        public SendMail()
        {
            SystemParameter.DATE_FORMAT = ConfigurationManager.AppSettings["Date_Format"].ToString();
            SystemParameter.DATETIME_FORMAT = ConfigurationManager.AppSettings["DateTime_Format"].ToString();
            SystemParameter.ADMINISTRATOR_EMAIL = ConfigurationManager.AppSettings["Administrator_Email"].ToString();
            SystemParameter.APPLICATION_ROOT_URL = ConfigurationManager.AppSettings["ApplicationRootUrl"].ToString();
            SystemParameter.APPLICATION_ROOT_URL_INTERNET = ConfigurationManager.AppSettings["ApplicationRootUrlInternet"].ToString();
            SystemParameter.CURRENT_VERSION = ConfigurationManager.AppSettings["CurrentVersion"].ToString();
        }

        #region 申明变量
        private string fileName;
        /// <summary>
        /// areaName
        /// </summary>
        private static string areaName = System.Configuration.ConfigurationSettings.AppSettings["AreaName"];

        /// <summary>
        /// password
        /// </summary>
        private static string password = System.Configuration.ConfigurationSettings.AppSettings["pwd"];

        /// <summary>
        /// serverName
        /// </summary>
        private static string serverName = System.Configuration.ConfigurationSettings.AppSettings["serverName"];

        /// <summary>
        /// fromMail
        /// </summary>
        private static string fromMail = System.Configuration.ConfigurationSettings.AppSettings["MailFrom"];

        #endregion

        #region 发送邮件接口
        /// <summary>
        /// 邮件的接口
        /// </summary>
        public void CreateMailForCommon(string templateCode, string headtile, string content, string mailTo, string mailCc, int priority, string filePath)
        {
            List<string> htmltextAndSubject = new List<string>();
            htmltextAndSubject = MailCreate4Common(templateCode, headtile, content);
            string html_text = htmltextAndSubject[0];
            string subject = htmltextAndSubject[1];
            InsertMail(mailTo, mailCc, subject, html_text, priority, filePath);
        }

        /// <summary>
        /// 将分数转换成字符
        /// </summary>
        /// <returns></returns>
        public string SwitchString(int mark)
        {
            string DescripStr = "";
            switch (mark)
            {
                case 1:
                    DescripStr = "Unsatisfied";
                    break;
                case 2:
                    DescripStr = "To be improved";
                    break;
                case 3:
                    DescripStr = "Acceptable";
                    break;
                case 4:
                    DescripStr = "Good";
                    break;
                case 5:
                    DescripStr = "Excellent";
                    break;
            }
            return DescripStr;

        }
    
        /// <summary>
        /// 替换邮件模板中的自定义参数(create by Cui Jiazhao 2010-7-30)
        /// </summary>
        /// <param name="templateContent">邮件模板的内容</param>
        /// <param name="paramKeyValue">参数名称和参数值</param>
        /// <returns></returns>
        private string SetParamValue(string templateContent, System.Collections.Hashtable paramKeyValue)
        {
            foreach (System.Collections.DictionaryEntry de in paramKeyValue)
            {
                templateContent = templateContent.Replace(de.Key.ToString(), de.Value.ToString());
            }
            return templateContent;
        }

        #endregion

        #region 创建基本模板
        /// <summary>
        /// 创建普通模板
        /// </summary>
        /// <param name="templatename">在数据库中模板的名称</param>
        /// <param name="headtitle">  邮件dear 后面的名称</param>
        /// <param name="content">  需要发送的内容</param>
        /// <returns></returns>
        public List<string> MailCreate4Common(string templateCode, string headtitle, string content)
        {
            string szSQL = string.Format("SELECT template_content,subject FROM COM_MailTemplate where template_code = '{0}'", templateCode);
            DataProvider dp = DataProvider.Instance("BE50BASE_ADMIN");
            DataTable dt = dp.ExecuteDataset(szSQL).Tables[0];
            string strTemplate_content = "";
            string strSubect = "";
            if (dt.Rows.Count > 0)
            {
                strTemplate_content = dt.Rows[0]["template_content"].ToString();
                strSubect = dt.Rows[0]["subject"].ToString();
            }
            else
            {
                throw new Exception(string.Format("COM_MailTemplate表找不到template_code = '{0}'记录！", templateCode));
            }
            dt.Dispose();
            string strhtml = CreateMailBody(strTemplate_content);
            strhtml = strhtml.Replace("<#SystemDateTime>", System.DateTime.Now.ToString("MM/dd/yyyy").Replace(@"-", @"/"));
            strhtml = strhtml.Replace("<#UserName>", headtitle);
            strhtml = strhtml.Replace("<#content>", content);
            List<string> mytemplate = new List<string>();
            mytemplate.Add(strhtml);
            mytemplate.Add(strSubect);
            return mytemplate;
        }
        #endregion

        #region 插入需要发送的邮件信息
        /// <summary>
        /// 将要发送的信息插入到邮件发送表中
        /// </summary>
        /// <param name="mail_to">不能为空</param>
        /// <param name="mail_cc"></param>
        /// <param name="mail_subject"></param>
        /// <param name="html_text"> 为邮件的发送的所有内容</param>
        /// <param name="priority"> 其中1为low，2为normal，3为high</param>
        ///  <param name="filename">  </param>
        /// <returns></returns>
        /// filepath样式为：@"C:\MailFileUpfile\123.7Z";
        public bool InsertMail(string mail_to, string mail_cc, string mail_subject, string html_text, int priority, string filepath)
        {
            string szSQL = string.Format(@"INSERT INTO COM_SendMail (mail_id,html_text,is_send,subject,mail_cc,mail_to,save_time,retry_times,status,attachment_file) VALUES 
                            ('{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7},{8},'{9}')",
                            System.Guid.NewGuid().ToString(),
                            html_text,
                            "N",
                            mail_subject,
                            mail_cc,
                            mail_to,
                            System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            0,
                            priority,
                            filepath != null ? filepath : "");
            DataProvider dp = DataProvider.Instance("BE50BASE_ADMIN");
            return dp.ExecuteNonQuery(szSQL) > 0;
        }
        #endregion

        #region 附件路径名和上传附件


        #endregion

        #region 上传附件到服务器指定的文件夹

        ///  // CommonUpfile upfile = new CommonUpfile();
        //upfile.UpLoadFile("C:\\mailfile\\test.doc", @"\\10.12.30.58\upfile");
        /// <summary>
        /// WebClient上传文件至服务器，默认不自动改名
        /// </summary>
        /// <param name="fileNamePath">文件名，全路径格式</param>
        /// <param name="uriString">服务器文件夹路径</param>
        public void UpLoadFile(string fileNamePath, string uriString)
        {
            UpLoadFile(fileNamePath, uriString, false);
        }

        /// <summary>
        /// WebClient上传文件至服务器
        /// </summary>
        /// <param name="fileNamePath">文件名，全路径格式</param>
        /// <param name="uriString">服务器文件夹路径</param>
        /// <param name="IsAutoRename">是否自动按照时间重命名</param>
        public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
        {
            string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
            string NewFileName = fileName;
            if (IsAutoRename)
            {
                NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
            }
            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
            if (uriString.EndsWith("/") == false) uriString = uriString + "/";
            uriString = uriString + NewFileName;
            //创建WebClient实例
            WebClient myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;
            // 要上传的文件
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            //FileStream fs = OpenFile();
            BinaryReader r = new BinaryReader(fs);
            byte[] postArray = r.ReadBytes((int)fs.Length);
            Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
            try
            {

                //使用UploadFile方法可以用下面的格式
                //myWebClient.UploadFile(uriString,"PUT",fileNamePath);
                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                    postStream.Close();
                    fs.Dispose();

                }
                else
                {
                    postStream.Close();
                    fs.Dispose();

                }

            }
            catch (Exception err)
            {
                postStream.Close();
                fs.Dispose();
                throw err;
            }
            finally
            {
                postStream.Close();
                fs.Dispose();
            }
        }

        #endregion

        #region 任务邮件
        /// <summary>
        /// 替换邮件内容
        /// </summary>
        /// <param name="template_content"></param>
        /// <param name="oldstring"></param>
        /// <param name="newstring"></param>
        /// <returns></returns>
        public string CreateMailBody(string template_content, string[] oldstring, string[] newstring)
        {
            for (int i = 0; i < oldstring.Length; i++)
            {
                template_content = template_content.Replace(oldstring[i], newstring[i]);
            }

            #region -- 套用邮件内容的外层框架 Add By Sammy Song 2010-08-31 --
            string mailBody = string.Empty;
            string webSiteRootUrl = SystemParameter.APPLICATION_ROOT_URL;
            HttpWebRequest webRequest
                    = (HttpWebRequest)WebRequest.Create(webSiteRootUrl
                    + "/FormContainer/Template/MailFrameTemplate.html");
            //请求服务
            WebResponse webResponse = webRequest.GetResponse();
            //返回信息
            Stream stream = webResponse.GetResponseStream();
            StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
            mailBody = reader.ReadToEnd();
            reader.Close();
            #endregion

            mailBody = mailBody.Replace("<#CurrentDateTime>", System.DateTime.Now.ToString(SystemParameter.DATETIME_FORMAT))
                    .Replace("<#WebRootURL>", string.Format("{0}{1}",webSiteRootUrl, "/portal/login.aspx"))
                    .Replace("<#MailBody>", template_content);
            return mailBody;
        }

        /// <summary>
        /// 替换邮件内容
        /// </summary>
        /// <param name="template_content"></param>
        /// <param name="oldstring"></param>
        /// <param name="newstring"></param>
        /// <returns></returns>
        public string CreateMailBody(string template_content)
        {
            #region -- 套用邮件内容的外层框架 Add By Sammy Song 2010-08-31 --
            string mailBody = string.Empty;
            string webSiteRootUrl = SystemParameter.APPLICATION_ROOT_URL;
            //webSiteRootUrl = "http://localhost:1976";
            HttpWebRequest webRequest
                    = (HttpWebRequest)WebRequest.Create(webSiteRootUrl
                    + "/FormContainer/Template/MailFrameTemplate.html");
            //请求服务
            WebResponse webResponse = webRequest.GetResponse();
            //返回信息
            Stream stream = webResponse.GetResponseStream();
            StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
            mailBody = reader.ReadToEnd();
            reader.Close();
            #endregion

            mailBody = mailBody.Replace("<#CurrentDateTime>", System.DateTime.Now.ToString(SystemParameter.DATETIME_FORMAT))
                    .Replace("<#WebRootURL>", webSiteRootUrl)
                    .Replace("<#MailBody>", template_content);
            return mailBody;
        }
        #endregion
    }
}
